<!-- 字典 -->
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="字典名称/编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleAddClick()">新增</el-button>
          <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" highlight-current-row :data="tableData" border class="data-table__content"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目标题" prop="title" />
        <el-table-column label="题目类型" prop="type" />
        <!-- 题目标签tag -->
        <el-table-column label="题目标签" prop="tags">
          <template #default="scope">
            <!-- 颜色随机 -->
            <el-tag style="margin: 5px;" v-for="tag in scope.row.tags" :key="tag" :type="getRandomColor()">{{ tag
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- 做题限时 -->
        <el-table-column label="做题限时" prop="timeLimit">
          <template #default="scope">
            {{ scope.row.timeLimit }}分钟
          </template>
        </el-table-column>
        <!-- 问题列表，二级表格展示 -->
        <el-table-column label="问题列表" width="400" prop="questions">
          <template #default="scope">
            <el-table :data="scope.row.questions" border>
              <el-table-column label="问题" prop="question" />
            </el-table>
          </template>
        </el-table-column>
        <!-- 题目完成状态 -->
        <el-table-column label="题目完成状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'completed' ? 'success' : 'danger'">
              {{ scope.row.status === 'completed' ? "已完成" : "未完成" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <!-- <el-button type="primary" link size="small" @click.stop="handleOpenDictData(scope.row)">
              <template #icon>
                <Collection />
              </template>
  字典数据
  </el-button> -->

            <el-button type="primary" link size="small" icon="edit" @click.stop="handleEditClick(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" icon="delete" @click.stop="handleDeleteQuestion(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="fetchData" />
    </el-card>

    <!--字典弹窗-->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="computedRules" label-width="100px">
        <el-card shadow="never">
          <el-form-item label="题目标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入题目标题" />
          </el-form-item>

          <el-form-item label="题目类型" prop="type">
            <el-input v-model="formData.type" placeholder="请输入题目类型" />
          </el-form-item>

          <el-form-item label="做题限时" prop="timeLimit">
            <el-input v-model="formData.timeLimit" placeholder="请输入做题限时" />
          </el-form-item>

          <!-- 题目标签 -->
          <el-form-item label="题目标签" prop="tags">
            <el-input-tag v-model="formData.tags" placeholder="Please input"
              aria-label="Please click the Enter key after input" />
          </el-form-item>
          <!-- 题目状态：选择 -->
          <el-form-item label="题目状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择题目状态">
              <el-option label="已完成" value="completed" />
              <el-option label="未完成" value="unfinished" />
            </el-select>
          </el-form-item>
          <!-- 题目列表 -->
          <el-form-item label="题目列表(JSON格式)">
            <!-- JSON 展示 -->
            <el-input v-model="formData.questions" :rows="10" type="textarea" placeholder="请输入题目列表" />
          </el-form-item>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitClick">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dict",
  inherititems: false,
});

import DictAPI, { DictPageQuery, DictPageVO, DictForm } from "@/api/system/dict.api";
import XIAOYU_API from "@/api/xiaoyu/index";
import router from "@/router";

// 删除题库数据
function handleDeleteQuestion(id: string) {
  XIAOYU_API.deleteQuestionData(id).then(() => {
    ElMessage.success("删除成功");
    handleQuery();
  }).catch(() => {
    ElMessage.error("删除失败");
  });

  // 刷新
  fetchData();
}

// 编辑题目数据
// function handleEditQuestion(data) {
//   console.log(data);

// }


const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tableData = ref<DictPageVO[]>();

// 获取随机颜色
const getRandomColor = () => {
  // primary || success || warning || danger ||info
  const colors = ['primary', 'success', 'warning', 'danger', 'info'];
  return colors[Math.floor(Math.random() * colors.length)];
};

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<DictForm>({});

const computedRules = computed(() => {
  const rules: Partial<Record<string, any>> = {
    name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
    dictCode: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
  };
  return rules;
});

// 获取数据
function fetchData() {
  loading.value = true;
  XIAOYU_API.getQuestionData().then((data) => {
    console.log(data.data);
    tableData.value = data.data;
    total.value = data.data.length;
  }).finally(() => {
    loading.value = false;
  });




  // DictAPI.getPage(queryParams)
  //   .then((data) => {
  //     tableData.value = data.list;
  //     total.value = data.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 行选择
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 新增字典
function handleAddClick() {
  dialog.visible = true;
  dialog.title = "新增题目数据";
  Object.assign(formData, {});
}

/**
 * 编辑字典
 *
 * @param id 字典ID
 */
function handleEditClick(row: DictForm) {
  dialog.visible = true;
  dialog.title = "编辑题目数据";
  row.questions = JSON.stringify(row.questions);
  Object.assign(formData, row);
}

// 提交字典表单
function handleSubmitClick() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      const id = formData.id;
      formData.tags = JSON.stringify(formData.tags);
      console.log(formData);
      if (id) {
        // DictAPI.update(id, formData)
        // 修改题目
        XIAOYU_API.updateQuestionData(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        // DictAPI.create(formData)
        // 新增题目
        XIAOYU_API.addQuestionData(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭字典弹窗
function handleCloseDialog() {
  dialog.visible = false;

  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}
/**
 * 删除字典
 *
 * @param id 字典ID
 */
function handleDelete(id?: number) {
  const attrGroupIds = [id || ids.value].join(",");
  if (!attrGroupIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      DictAPI.deleteByIds(attrGroupIds).then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开字典项
function handleOpenDictData(row: DictPageVO) {
  router.push({
    path: "/system/dict-item",
    query: { dictCode: row.dictCode, title: "【" + row.name + "】字典数据" },
  });
}

onMounted(() => {
  handleQuery();
});
</script>
